<template>
  <div class="rectification-manager" ref="rectification">
    <div class="rectification-manager__header">
      <div class="template-button-container">
        <div
          v-for="item in list"
          :key="item.value"
          @click="handleActive(item.value)"
          :class="activeName === item.value ? 'active button' : 'button'"
        >
          {{ item.name }}
        </div>
      </div>
      <div>
        <el-button @click="handleSubmitAll" class="rectification-manager__buts" type="primary">发起客户确认</el-button>
        <el-button @click="handleSubmitPlay" class="rectification-manager__buts" type="primary">批量收款</el-button>
      </div>
    </div>

    <div class="rectification-container">
      <div class="filter-container">
        <el-form :model="tableParams" label-width="120">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="单据单号">
                <el-input placeholder="请输入" v-model="tableParams.reformNo" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发起人">
                <!-- TODO: 下拉框搜索用户，封装组件 -->
                <el-input placeholder="请输入" v-model="tableParams.submitUserName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="责任人">
                <el-input placeholder="请输入" v-model="tableParams.assignBlameUserName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发起时间">
                <el-date-picker
                  v-model="dateRange"
                  :clearable="false"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  @change="changeTime"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="nameTitle + '分类'">
                <el-cascader
                  style="width: 100%"
                  v-model="tableParams.reformTypeIds"
                  :options="rectificationOptions"
                  :props="rectificationProps"
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联客户">
                <el-input placeholder="请输入" v-model="tableParams.customerName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="判责状态">
                <el-select placeholder="请选择" v-model="tableParams.assignBlameStateArr" multiple>
                  <el-option v-for="item in judgmentStatus" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否延期">
                <el-select placeholder="请选择" v-model="tableParams.isDelay">
                  <el-option label="是" :value="true" />
                  <el-option label="否" :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="nameTitle + 'ID'">
                <el-input placeholder="请输入" v-model="tableParams.reformId" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联任务审批ID">
                <el-input placeholder="请输入" v-model="tableParams.formInstanceId" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="任务ID">
                <el-input placeholder="请输入" v-model="tableParams.stageTaskId" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="filter-container-buttons">
                <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
                <el-button type="primary" plain :icon="RefreshRight" @click="handelResetFilter">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="tabs-sticky">
        <div class="tabs-content">
          <el-tabs v-model="tableParams.reformState" class="demo-tabs" @tab-change="handleTabsChange">
            <el-tab-pane :name="0" label="全部"></el-tab-pane>
            <el-tab-pane :name="1">
              <template #label>
                <span class="custom-tabs-label">
                  <span>待审批</span> <span v-if="stateCounts?.approval">({{ stateCounts?.approval }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="审批中" :name="7">
              <template #label>
                <span class="custom-tabs-label">
                  <span>审批中</span> <span v-if="stateCounts?.approving">({{ stateCounts?.approving }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="审批未通过" :name="5">
              <template #label>
                <span class="custom-tabs-label">
                  <span>审批未通过</span> <span v-if="stateCounts?.approvalFailed">({{ stateCounts?.approvalFailed }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="待发起客户确认" :name="8">
              <template #label>
                <span class="custom-tabs-label">
                  <span>待发起客户确认</span>
                  <span v-if="stateCounts?.pendingCustomerConfirmation">({{ stateCounts?.pendingCustomerConfirmation }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="客户确认中" :name="9">
              <template #label>
                <span class="custom-tabs-label">
                  <span>客户确认中</span>
                  <span v-if="stateCounts?.customerConfirming">({{ stateCounts?.customerConfirming }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="客户拒绝" :name="10">
              <template #label>
                <span class="custom-tabs-label">
                  <span>客户拒绝</span> <span v-if="stateCounts?.customerRefused">({{ stateCounts?.customerRefused }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="待收款" :name="11">
              <template #label>
                <span class="custom-tabs-label">
                  <span>待收款</span> <span v-if="stateCounts?.pendingPayment">({{ stateCounts?.pendingPayment }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="待开始" :name="2">
              <template #label>
                <span class="custom-tabs-label">
                  <span>待开始</span> <span v-if="stateCounts?.pendingStart">({{ stateCounts?.pendingStart }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="进行中" :name="3">
              <template #label>
                <span class="custom-tabs-label">
                  <span>进行中</span> <span v-if="stateCounts?.inProgress">({{ stateCounts?.inProgress }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="已完成" :name="4">
              <template #label>
                <span class="custom-tabs-label">
                  <span>已完成</span> <span v-if="stateCounts?.completed">({{ stateCounts?.completed }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="已作废" :name="6">
              <template #label>
                <span class="custom-tabs-label">
                  <span>已作废</span> <span v-if="stateCounts?.invalid">({{ stateCounts?.invalid }})</span>
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="table-container-filter">
          <el-button style="width: 140px" type="primary" plain @click="handelExport" :loading="isLoadingExport"
            >按查询条件导出
          </el-button>
          <el-button style="width: 140px" v-show="selectedReformIds.length" type="primary" plain @click="handelBatchClearing"
            >批量清空
          </el-button>
        </div>
      </div>
      <div class="table-container" element-loading-text="数据加载中..." v-loading="isLoadingTable">
        <el-table
          ref="reformTableRef"
          :data="tableData"
          stripe
          style="width: 100%"
          border
          :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
          reserve-selection
          row-key="reformId"
          @selection-change="selectionChange"
          :height="tableHeight"
        >
          <el-table-column type="selection" reserve-selection width="55" fixed="left" />
          <el-table-column :label="nameTitle + '分类'" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ reformTypeLabel(row).value }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="customerName" label="关联客户" show-overflow-tooltip />
          <el-table-column label="问题描述" show-overflow-tooltip prop="reformDesc" />
          <el-table-column label="解决方案" show-overflow-tooltip prop="solution" />
          <el-table-column label="已收款/应收款" show-overflow-tooltip prop="" width="120">
            <template #default="{ row }">
              {{ Number(row.alreadyPutAmount) <= 0 ? "0.00" : row.alreadyPutAmount }}/{{
                Number(row.shouldAmount) <= 0 ? "0.00" : row.shouldAmount
              }}
            </template>
          </el-table-column>
          <el-table-column label="已退款/应退款" show-overflow-tooltip prop="" width="120">
            <template #default="{ row }">
              {{ Number(row.alreadyRefundAmount) <= 0 ? "0.00" : row.alreadyRefundAmount }}/{{
                Number(row.notRefundAmount) <= 0 ? "0.00" : row.notRefundAmount
              }}
            </template>
          </el-table-column>
          <el-table-column label="责任人" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.assignBlameUserNames">{{ row.assignBlameUserNames }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="判责状态" width="100" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="judgment-status" :class="`judgment-status-${judgmentLabel(row).value[0]}`">
                {{ judgmentLabel(row).value[1] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="nameTitle + '状态'" width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="reform-state" :class="`reform-state-${reformMapLabel(row).value[0]}`">
                {{ reformMapLabel(row).value[1] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="判责单号" prop="assignBlameNo" show-overflow-tooltip/>
          <el-table-column label="发起人" prop="submitUserName" />
          <el-table-column prop="submitTime" label="发起时间" width="120" show-overflow-tooltip></el-table-column>
          <!-- 全部、待开始、进行中、已完成显示该字段，其它状态不显示      -->
          <el-table-column
            prop="expectDays"
            label="预计工期"
            show-overflow-tooltip
            v-if="showTableLabel.includes(tableParams.reformState)"
          >
            <template #default="{ row }">
              {{ row.expectDays > 0 ? row.expectDays + "天" : "-" }}
            </template>
          </el-table-column>
          <!-- 全部、待开始、进行中、已完成显示该字段，其它状态不显示     -->
          <el-table-column
            prop="delayDays"
            label="延期"
            show-overflow-tooltip
            v-if="showTableLabel.includes(tableParams.reformState)"
          >
            <template #default="{ row }">
              {{ row.delayDays > 0 ? row.delayDays + "天" : "-" }}
            </template>
          </el-table-column>
          <!-- 全部、待开始、进行中、已完成显示该字段，其它状态不显示 -->
          <el-table-column
            prop="packagePlainStartDate"
            label="任务开始时间"
            show-overflow-tooltip
            width="120"
            v-if="showTableLabel.includes(tableParams.reformState)"
          />
          <!-- 全部、待开始、进行中、已完成显示该字段，其它状态不显示      -->
          <el-table-column
            prop="packagePlainEndDate"
            label="任务结束时间"
            show-overflow-tooltip
            width="120"
            v-if="showTableLabel.includes(tableParams.reformState)"
          />
          <el-table-column prop="reformNo" label="单据单号" show-overflow-tooltip />
          <el-table-column prop="reformId" :label="nameTitle + 'ID'" show-overflow-tooltip />
          <el-table-column label="关联任务审批ID" prop="formInstanceId" width="160" show-overflow-tooltip/>
          <el-table-column label="任务ID" prop="stageTaskId" show-overflow-tooltip/>
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <div class="table-operate">
                <el-button
                  v-has-permission="button.permission"
                  v-for="button in getVisibleButtons(row)"
                  :key="button.text"
                  type="primary"
                  link
                  @click="button.action"
                >
                  {{ button.text }}
                </el-button>
                <div v-if="showDropdownitem(row)">
                  <el-dropdown>
                    <span class="el-dropdown-link" style="font-size: 14px"
                      >展开
                      <el-icon class="el-icon--left">
                        <arrow-down />
                      </el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="item in filteredDropdownItems(row)"
                          :key="item.command"
                          :command="item.command"
                          @click="item.action"
                        >
                          <el-button v-has-permission="item.permission" type="text" style="height: 22px"
                            >{{ item.text }}
                          </el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <custom-pagination
      :total="listTotal"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      @pagination="handelPage"
    >
    </custom-pagination>
    <div class="delete-dialog">
      <!-- 作废弹窗   -->
      <el-dialog :show-close="false" v-model="centerDialogVisible" title="作废" width="306px" center>
        <span>你确定要作废此单据吗？</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDeleteOk">作废</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 发起客户确认   -->
      <el-dialog :show-close="false" v-model="visible" title="发起客户确认" width="450px" center>
        <template #header>
          <div style="font-weight: 400; font-size: 18px; color: #3d3d3d; display: flex; align-items: center">
            <div style="width: 6px; height: 6px; background: #409eff; border-radius: 50%; margin-right: 10px"></div>
            发送客户确认 <span style="color: #86909c; font-size: 12px">（仅需客户确认的单据会向客户发送通知）</span>
          </div>
        </template>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" label-position="top">
          <el-form-item label="请选择关联客户" prop="customerIds">
            <el-select placeholder="选择择" filterable multiple v-model="ruleForm.customerIds">
              <el-option
                v-for="item in allCustomers"
                :label="item.customerName"
                :value="item.customerId"
                :key="item.customerId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="请选择售后单状态" prop="reformState">
            <el-select placeholder="选择择" v-model="ruleForm.reformState">
              <el-option label="全部" :value="0" />
              <el-option label="待发起客户确认" :value="8" />
              <el-option label="客户拒绝" :value="10" />
            </el-select>
          </el-form-item>
          <el-form-item label="请选择售后单类型" prop="afterSalesType">
            <el-select placeholder="选择择" v-model="ruleForm.afterSalesType">
              <el-option label="全部" :value="0" />
              <el-option label="整改" :value="1" />
              <el-option label="增减项" :value="3" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer" style="text-align: center">
            <el-button @click="visible = false" color="#F2F3F5">取消</el-button>
            <el-button type="primary" @click="handleSubmit">发起确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 批量收款   -->
    <pay-dialog ref="payDialogRef" />

    <!-- 任务明细 start-->
    <div class="client-follow-drawer">
      <el-drawer v-model="isTaskDetailDrawer" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-follow-up" v-loading="isTaskDetailLoading" element-loading-text="数据加载中...">
          <title-view title="任务明细" isClose @close="handelCloseTaskDetail" />
          <div class="content-tasks">
            <div class="content-tasks-list" ref="instructionsTitle">
              <template v-if="taskList.length">
                <div class="content-tasks-list-item" v-for="item in taskList" :key="item.stageTaskId">
                  <div class="list-item-options">
                    <div class="list-item-options-icon"></div>
                    <div class="list-item-options-type">【{{ nameTitle }}】</div>
                    <div class="list-item-options-label">{{ item.taskName }}</div>
                    <el-button type="primary" link @click="handelShowInstructions(item)">补充说明</el-button>
                  </div>
                  <div class="list-item-info">
                    <div class="list-item-info-item"><span>人员：</span>{{ item.userName }}</div>
                    <div class="list-item-info-item">
                      <span>任务开始时间：</span>
                      <span>{{ taskDetailStarTime(item).value }}</span>
                      <span class="view-form" v-if="item.status === 3" @click="handelCheckStage(item)">查看</span>
                    </div>
                  </div>
                </div>
              </template>
              <el-empty v-else />
            </div>
          </div>
        </div>
      </el-drawer>
      <Transition name="fade">
        <div class="instructions-container" ref="instructionsContainer" v-show="instructionsVisible">
          <div class="arrow"></div>
          <title-view title="补充说明" isClose @close="handelCloseInstructions" />
          <div class="editor-container" v-html="instructionsText"></div>
        </div>
      </Transition>
    </div>
    <!--  start 已完成任务查看详情-->
    <formDetailDialog v-if="showFormDetail" v-model="showFormDetail" :currentFormParams="currentFormParams"></formDetailDialog>

    <!-- 任务明细 end-->
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, onActivated, onUnmounted, ref } from "vue";
import formDetailDialog from "../clientInfo/components/rectification/components/formDetailDialog.vue";
import { ArrowDown, RefreshRight, Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { documentFlow } from "@/utils/downFile";
import useComputedParams from "@/hooks/useComputedParams";
import { judgmentStatus, list } from "./config";
import {
  deleteTask,
  rectificationExport,
  rectificationManagerList,
  rectificationTypeTree,
  reformDelete,
  startTask,
  stateCount,
  queryAllCustomers,
  sendCustomerConfirmBatch,
  sendCustomerConfirmSingle,
  revokeCustomer
} from "@/apis/rectificationManager";
import useTagsViewStore from "@/store/modules/tagsView";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import _ from "lodash";
import { rectificationDetail } from "@/apis/rectification";

const nameTitle = ref("整改");
const { proxy } = getCurrentInstance();
const router = useRouter();
const tagsViewStore = useTagsViewStore();
const activeName = ref("second");
const stateCounts = ref(null);
const instructionsLeft = ref("0px");
const instructionsTop = ref("40px");
const arrowLeft = ref("0px");
const arrowTop = ref("40px");
const instructionsWidth = ref(400);
const taskList = ref([]);
const instructionsText = ref("");
const isTaskDetailDrawer = ref(false);
const instructionsVisible = ref(false);
const isTaskDetailLoading = ref(false);
const payDialogRef = ref(null);
const centerDialogVisible = ref(false);
const isLoadingTable = ref(false);
const visible = ref(false);
const allCustomers = ref([]);
const ruleForm = ref({
  customerIds: [],
  reformState: 0,
  afterSalesType: 0
});
const ruleFormRef = ref();
const rules = ref({
  customerIds: { required: true, message: "请选择关联客户", trigger: "blur" },
  reformState: { required: true, message: "请选择售后单状态", trigger: "change" },
  afterSalesType: { required: true, message: "请选择售后单类型", trigger: "change" }
});
const showTableLabel = ref([0, 2, 3, 4]);
const tableHeight = ref(0);
const rectification = ref();

const initTableParams = {
  current: 1,
  size: 10,
  reformNo: "",
  submitUserName: "",
  submitUserId: "",
  assignBlameUserName: "",
  assignBlameUserId: "",
  assignBlameStateArr: [],
  reformState: 0,
  reformTypeIds: [],
  beginSubmitTime: "",
  endSubmitTime: "",
  reformId: "",
  reasonId: "",
  customerName: ""
};
const dateRange = ref([]);
const tableParams = ref({ ...initTableParams });
const tableData = ref([]);
const listTotal = ref(0);

const disabledDate = time => {
  const now = dayjs().startOf("date");
  return time.valueOf() > now.valueOf();
};
const changeTime = time => {
  if (time) {
    const startDate = new Date(time[0]);
    const endDate = new Date(time[1]);
    const diff = endDate.getTime() - startDate.getTime();
    const diffInDays = diff / (1000 * 60 * 60 * 24);
    const diffInYears = diffInDays / 365;
    if (diffInYears > 2) {
      dateRange.value = [];
      ElMessage({ message: "最大时间跨度为2年,请重新选择！", type: "error" });
    }
  }
};
const handelCloseTaskDetail = () => {
  isTaskDetailDrawer.value = false;
  instructionsVisible.value = false;
};
const handelShowInstructions = async data => {
  instructionsVisible.value = true;
  await nextTick();
  instructionsText.value = data.remark;
  const instructionsTitleEl = proxy.$refs.instructionsTitle;
  const instructionsTitleRect = instructionsTitleEl.getBoundingClientRect();
  instructionsLeft.value = `${instructionsTitleRect.left - instructionsWidth.value - 40}px`;
  instructionsTop.value = `${instructionsTitleRect.top}px`;
  arrowLeft.value = `${instructionsTitleRect.left - 41}px`;
  arrowTop.value = `${instructionsTitleRect.top + 10}px`;
  window.addEventListener("resize", handleResize);
};
let initialInstructionsWidth;
const handleResize = _.debounce(() => {
  const instructionsTitleEl = proxy.$refs.instructionsTitle;
  if (!instructionsTitleEl) return;
  const instructionsTitleRect = instructionsTitleEl.getBoundingClientRect();
  // 获取初始宽度，确保在首次渲染后进行
  if (!initialInstructionsWidth) {
    initialInstructionsWidth = instructionsWidth.value;
  }
  instructionsLeft.value = `${instructionsTitleRect.left - initialInstructionsWidth - 40}px`;
  instructionsTop.value = `${instructionsTitleRect.top}px`;
  arrowLeft.value = `${instructionsTitleRect.left - 41}px`;
  arrowTop.value = `${instructionsTitleRect.top + 10}px`;
}, 10);
const taskDetailStarTime = useComputedParams(item => {
  let label = "";
  (() => {
    switch (item.status) {
      case 1:
        return (label = item.plainStartDate ? dayjs(item.plainStartDate).format("YYYY-MM-DD") : "未设置");
      case 2:
        return (label = "已开始");
      case 3:
        return (label = "已完成");
      default:
        return (label = "未知");
    }
  })();
  return label;
});

const handelCloseInstructions = () => {
  window.removeEventListener("resize", handleResize);
  instructionsVisible.value = false;
};
const handelTaskDetail = async dataItem => {
  isTaskDetailDrawer.value = true;
  try {
    isTaskDetailLoading.value = true;
    const { data } = await rectificationDetail(dataItem.reformId);
    taskList.value = data || [];
    isTaskDetailLoading.value = false;
  } catch (err) {
    isTaskDetailLoading.value = false;
  }
};

//查看详情
const showFormDetail = ref(false);
const currentFormParams = ref({});
const handelCheckStage = dataItem => {
  showFormDetail.value = true;
  currentFormParams.value = dataItem;
};
// 点击切换tabs
const handleActive = type => {
  nameTitle.value = type === "first" ? "增减项" : "整改";
  activeName.value = type;
  tableData.value = [];
  tableParams.value = {
    ...initTableParams
  };
  initData();
};
const setDate = () => {
  // 默认选中六个时间
  const recentSixMonths = getRecentSixMonthsRange();
  dateRange.value = [recentSixMonths.start, recentSixMonths.end];
};

setDate();
const getStateCount = async () => {
  const { data } = await stateCount(handelConditions());
  stateCounts.value = data || null;
};
// 选择售后状态
const handleTabsChange = e => {
  tableParams.value.reformState = e;
  handelSearch();
};
const buttons = row => {
  return [
    {
      command: 0,
      condition: () => row.reformState !== 6,
      text: "详情",
      action: () => handelGoDetail(row)
    },
    {
      command: 1,
      condition: () => [1, 5, 8, 10].includes(row.reformState),
      text: "编辑",
      permission: ["crm:rectificationManager:edit"],
      action: () => handelGoEdit(row)
    },
    {
      command: 2,
      condition: () => ![10, 11].includes(row.assignBlameState) && [2, 3, 4, 11].includes(row.reformState),
      text: "判责",
      permission: ["crm:rectificationManager:judgment"],
      action: () => handelJudgment(row)
    },
    {
      command: 3,
      condition: () =>
        [1, 5, 8, 10, 2, 11].includes(row.reformState) &&
        Number(row.alreadyPutAmount) === 0 &&
        Number(row.alreadyRefundAmount) === 0,
      text: "作废",
      action: () => handleDelete(row)
    },
    {
      command: 4,
      condition: () => [7].includes(row.reformState),
      text: "撤销审批",
      action: () => handleRevocation(row, 0)
    },
    {
      command: 6,
      condition: () => [8, 10].includes(row.reformState),
      text: "发起客户确认",
      action: () => handleRevocation(row, 1)
    },
    {
      command: 7,
      condition: () => [9].includes(row.reformState),
      text: "撤销客户确认",
      action: () => handleRevocation(row, 2)
    },
    {
      command: 8,
      condition: () => [11].includes(row.reformState),
      text: "确认" + nameTitle.value,
      action: () => handleRevocation(row, 3),
      permission: ["crm:rectificationManager:changes"]
    },
    {
      command: 9,
      condition: () => true,
      text: "任务明细",
      action: () => handelTaskDetail(row)
    },
    {
      command: 10,
      condition: () =>
        [2, 3, 4, 11].includes(row.reformState) && Number(row.shouldAmount) > Number(row.alreadyPutAmount) && row.slipId,
      text: "收款",
      action: () => handlePlayVisible(row)
    }
  ];
};
// 收款
const handlePlayVisible = row => {
  payDialogRef.value.open({
    customerId: row.customerId,
    customerName: row.customerName,
    reformId: [row.reformId],
    slipId: [row.slipId],
    sumMoneys: ((Number(row.shouldAmount || 0) * 100 - Number(row.alreadyPutAmount || 0) * 100) / 100).toFixed(2)
  });
};

//定义按钮
const getVisibleButtons = row => {
  // 过滤可见按钮
  const filteredButtons = buttons(row).filter(btn => btn.condition());
  return filteredButtons.length <= 2 ? filteredButtons : [filteredButtons[0]];
};
//判断按钮显示个数是否大于2 大于2返回true
const showDropdownitem = row => {
  const arryButtonCount = buttons(row).reduce((count, item) => count + item.condition(), 0);
  return arryButtonCount > 2;
};
// 过滤掉第一个满足条件的下拉项
const filteredDropdownItems = row => {
  const visibleItems = buttons(row).filter(item => item.condition());
  visibleItems.shift();
  return visibleItems;
};

// 工具函数，用于计算最近六个月的日期范围
function getRecentSixMonthsRange() {
  const now = dayjs();
  const start = now.subtract(6, "month").format("YYYY-MM-DD");
  const end = now.format("YYYY-MM-DD");
  return {
    start,
    end
  };
}

// 撤销审批
const handleRevocation = (row, i) => {
  const nameList = ["撤销审批", "发起客户确认", "撤销客户确认", "确认" + nameTitle.value];
  const textList = ["你确定要撤销此单据吗?", "确定发起客户确认？", "确定撤回消息确认？", `确定不收款可开启任务吗？`];
  if (row.isBatchMsg === 1 && i === 2) {
    textList[i] = "本次会撤销一同发起客户确认的多个单据，确定撤销？";
  }
  ElMessageBox.confirm(textList[i], nameList[i], {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    center: true,
    customClass: "message-box",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        switch (i) {
          case 0:
            await deleteTask(row.reformId);
            initData();
            ElMessage({
              type: "success",
              message: "撤销成功"
            });
            done();
            break;
          case 1:
            await sendCustomerConfirmSingle(row.reformId);
            ElMessage({
              type: "success",
              message: "发起成功"
            });
            initData();
            done();
            break;
          case 2:
            await revokeCustomer(row.msgId);
            ElMessage({
              type: "success",
              message: "撤销成功"
            });
            initData();
            done();
            break;
          case 3:
            await startTask({ reformId: row.reformId });
            ElMessage({
              type: "success",
              message: "确认" + nameTitle.value + "成功"
            });
            initData();
            done();
            break;
        }
      } else {
        done();
      }
    }
  });
};

// 点击批量发起客户确认
const handleSubmitAll = async () => {
  ruleForm.value = {
    customerIds: [],
    reformState: 0,
    afterSalesType: 0
  };
  const { data } = await queryAllCustomers();
  allCustomers.value = data || [];
  visible.value = true;
};
// 批量发起客户确认
const handleSubmit = async () => {
  await ruleFormRef.value.validate(async valid => {
    if (!valid) return;
    const { msg } = await sendCustomerConfirmBatch(ruleForm.value);
    ElMessage.success(msg);
    initData();
    visible.value = false;
  });
};
// 查询参数
const handelConditions = () => {
  const postData = {
    ...tableParams.value,
    reformState: tableParams.value.reformState === 0 ? "" : tableParams.value.reformState
  };
  if (dateRange.value?.length >= 2) {
    postData.beginSubmitTime = dateRange.value[0];
    postData.endSubmitTime = dateRange.value[1];
  }
  postData.firstReasonId = tableParams.value.reasonId[0] || "";
  postData.secondReasonId = tableParams.value.reasonId[1] || "";
  postData.reasonId = tableParams.value.reasonId[2] || "";
  postData.afterSalesType = activeName.value === "first" ? "3" : "1";
  return postData;
};
// 获取列表数据
const getRectificationManagerList = async () => {
  try {
    isLoadingTable.value = true;
    const { data } = await rectificationManagerList(handelConditions());
    tableData.value = data?.list ?? [];
    listTotal.value = data?.total ?? 0;
    isLoadingTable.value = false;
  } catch (err) {
    isLoadingTable.value = false;
  }
};
const setHeight = () => {
  nextTick(() => {
    tableHeight.value = rectification.value?.getBoundingClientRect().height - 139 - 40 - 30;
  });
};
// 分页查询
const handelPage = () => {
  tableData.value = [];
  getRectificationManagerList();
  getStateCount();
};
// 详情
const handelGoDetail = data => {
  router.push({
    path: "/after-sales-order-detail",
    query: {
      reformId: data.reformId,
      show: 1
    }
  });
};

/**
 * 过滤
 */
// 类型tree
const rectificationOptions = ref([]);
const rectificationProps = {
  value: "reformTypeId",
  label: "reformTypeName",
  multiple: true
};
const getRectificationTypeTree = async () => {
  const { data } = await rectificationTypeTree(nameTitle.value === "整改" ? 1 : 3, "");
  rectificationOptions.value = data ?? [];
};
// TODO：下拉框搜索，可封装组件

const handelSearch = () => {
  tableParams.value.current = 1;
  tableData.value = [];
  getRectificationManagerList();
  getStateCount();
};
const handelResetFilter = () => {
  tableParams.value = {
    ...initTableParams
  };
  setDate();
  getRectificationManagerList();
  getStateCount();
};

/**
 * 批量核实
 */

const selectedReformIds = ref([]);
// 只能选择已判责、已核实任务进行核实
const selectionChange = val => {
  selectedReformIds.value = val.map(item => item.reformId);
};
const handelBatchClearing = () => {
  proxy.$refs.reformTableRef.clearSelection();
  selectedReformIds.value = [];
};

/**
 * 根据条件导出
 */
const isLoadingExport = ref(false);
const handelExport = async () => {
  try {
    isLoadingExport.value = true;
    const res = await rectificationExport(handelConditions());
    isLoadingExport.value = false;
    documentFlow(res, `${nameTitle.value}管理`, "xlsx");
  } catch (err) {
    isLoadingExport.value = false;
  }
};

const reformId = ref("");
// 跳转判责
const handelJudgment = row => {
  reformId.value = row.reformId;
  router.push({ path: "/judgment-add", query: { reformId: row.reformId } });
};

/**
 * 状态
 */
const judgmenMap = new Map([
  [1, ["warning", "未判责"]],
  [2, ["success", "已判责"]],
  [3, ["success", "已核实"]],
  [4, ["danger", "审批未通过"]],
  [5, ["warning", "待发起确认"]],
  [6, ["primary", "确认中"]],
  [7, ["success", "已核实"]],
  [8, ["danger", "责任人拒绝"]],
  [9, ["primary", "核实中"]],
  [10, ["primary", "审批中"]],
  [11, ["info", "已作废"]]
]);

const judgmentLabel = useComputedParams(data => {
  return judgmenMap.has(data.assignBlameState) ? judgmenMap.get(data.assignBlameState) : ["danger", "未知"];
});
const reformMap = new Map([
  [1, ["warning", "待审核"]],
  [2, ["warning", "待开始"]],
  [3, ["primary", "进行中"]],
  [4, ["success", "已完成"]],
  [5, ["danger", "未通过"]],
  [6, ["info", "已作废"]],
  [7, ["primary", "审批中"]],
  [8, ["warning", "待发起客户确认"]],
  [9, ["primary", "客户确认中"]],
  [10, ["danger", "客户拒绝"]],
  [11, ["warning", "待收款"]]
]);
const reformMapLabel = useComputedParams(data => {
  return reformMap.has(data.reformState) ? reformMap.get(data.reformState) : ["danger", "未知"];
});
/**
 * 分类
 */
const reformTypeLabel = useComputedParams(data => {
  let html = "";
  if (data.firstReformTypeName) {
    html += data.firstReformTypeName + "-";
  }
  if (data.secondReformTypeName) {
    html += data.secondReformTypeName + "-";
  }
  if (data.reformTypeName) {
    html += data.reformTypeName;
  }
  return html;
});

const initData = () => {
  tagsViewStore.isRefresh = false;
  getStateCount();
  getRectificationTypeTree();
  getRectificationManagerList();
};

onActivated(() => {
  tagsViewStore.isRefresh && handelResetFilter();
});

const handleDelete = row => {
  centerDialogVisible.value = true;
  reformId.value = row.reformId;
};
const handleDeleteOk = async () => {
  await reformDelete(reformId.value);
  centerDialogVisible.value = false;
  initData();
};
// 编辑
const handelGoEdit = row => {
  reformId.value = row.reformId;
  if (row.exchangeBudgetId) {
    const baseRouter = window.microApp.router.getBaseAppRouter();
    const routeUrl = baseRouter.resolve({
      path: "/designer/quote-price/following/change",
      query: {
        budgetId: row.budgetId,
        contractId: row.contractId,
        customerId: row.customerId,
        reformId: row.reformId,
        afterSalesType: activeName.value === "first" ? "3" : "1"
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    router.push({
      path: "/after-sales-order",
      query: {
        reformId: reformId.value,
        afterSalesType: nameTitle.value === "整改" ? 1 : 3
      }
    });
  }
};

// 批量收款
const handleSubmitPlay = () => {
  payDialogRef.value.openVisible();
};

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});
initData();
setHeight();
</script>

<style scoped lang="scss">
@use "rectificationManager";
</style>
<style lang="scss" scoped>
@use "@/assets/styles/mixin";

.rectification-manager {
  height: calc(100% - 20px);
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: scroll;
  box-shadow: 4px 5px 16px 0 rgba(0, 0, 0, 0.04);
  border-radius: 8px;

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 17px 0;
    border-bottom: 1px solid #e2e8f0;
    margin-bottom: 20px;
  }
}

.select-user-popper {
  border: 1px solid #0052d9 !important;
  box-shadow: 0 0 0 2px #d9e1ff !important;
  border-radius: 3px;

  .el-select-dropdown__header {
    padding: 10px 5px 4px 5px !important;
  }

  .el-scrollbar__view > .el-select-dropdown__item {
    @include mixin.flex-align;
    padding-left: 10px;
    padding-right: 10px;
    //font-size: 12px;
    color: #3d3d3d;
    line-height: 22px;
  }

  .el-popper__arrow::before {
    display: none;
  }
}

.tabs-sticky {
  position: sticky;
  top: 0px;
  background: #ffffff;
  z-index: 99;
}

// 操作说明
.instructions-container {
  @include mixin.flex-column;
  overflow: auto;
  position: fixed;
  left: v-bind(instructionsLeft);
  top: v-bind(instructionsTop);
  z-index: 9999;
  width: 400px;
  height: 90vh;
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;

  .arrow {
    position: fixed;
    left: v-bind(arrowLeft);
    top: v-bind(arrowTop);
    z-index: 9999;
    width: 0;
    height: 0;
    border: 14px solid transparent;
    border-left: 14px solid #fff;
  }

  .editor-container {
    flex: 1;
    width: 100%;
    overflow: auto;
  }
}

.view-form {
  margin-left: 10px;
  display: inline-block;
  color: #007dff !important;
  cursor: pointer;
}
</style>
